import sys
import os
from os import path
from datetime import datetime, timedelta

import chardet


def backup(f):
    i=1
    bak = f
    while path.exists(bak):  #f肯定是存在的,所以第一次循环tmp也必定存在
        fn,ex = path.splitext(f)
        bak = fn + '.bak' + str(i) + ex
        i+=1
    os.rename(f,bak)
    return bak


src = sys.argv[1]
delta = int(input('输入调整的秒数,负数表示提前'))
if path.isdir(src):
    targets = tuple(map(lambda x: path.join(src, x), os.listdir(src)))
else:
    targets = (src,)
for target in targets:
    if target.endswith('.srt') or target.endswith('.ass') or target.endswith('.ssa'):
        bak = backup(target)
        with open(bak,'br') as chde:
            samp=chde.read(256)
            srccoding=chardet.detect(samp).get('encoding')
            if not srccoding:
                srccoding='gb2312'
            else:
                print(srccoding)
        try:
            with open(target, 'w', encoding=srccoding) as dst:
                with open(bak, encoding=srccoding,errors='ignore') as f:
                    while(1):
                        line=f.readline()
                        if not line:
                            break
                        # if line.isspace():
                        #     continue
                        if'-->' in line:
                            line = line.replace(':', ',')
                            st = list(
                                map(lambda x: int(x), line[:line.index(' ')].split(',')))
                            ed = list(
                                map(lambda x: int(x), line[line.rindex(' ')+1:].split(',')))
                            stime = datetime(10, 1, 1, st[0], st[1], st[2], st[3]*1000
                                            )+timedelta(seconds=delta)
                            edtime = datetime(10, 1, 1, ed[0], ed[1], ed[2], ed[3]*1000
                                            )+timedelta(seconds=delta)
                            line = '%02d:%02d:%02d,%03d --> %02d:%02d:%02d,%03d\n' % (
                                stime.hour, stime.minute, stime.second, stime.microsecond/1000,
                                edtime.hour, edtime.minute, edtime.second, edtime.microsecond/1000)
                        if line.startswith('Dialogue:'):
                            # if'Marked=' in line:
                            #     seg1 = line[:40]
                            #     seg2 = line[41:]
                            # else:
                            pre,seg1,seg2,*rest=line.split(',')
                            # segs = seg1.split(',')
                            st = list(
                                map(lambda x: int(x), seg1.replace(':', '.').split('.')))
                            if st[1]<1:
                                dst.write(line)
                                continue
                            ed = list(
                                map(lambda x: int(x), seg2.replace(':', '.').split('.')))
                            stime = datetime(10, 1, 1, st[0], st[1], st[2], st[3]*1000
                                            )+timedelta(seconds=delta)
                            etime = datetime(10, 1, 1, ed[0], ed[1], ed[2], ed[3]*1000
                                            )+timedelta(seconds=delta)
                            line = '%s,%02d:%02d:%02d.%02d,%02d:%02d:%02d.%02d,%s' % (pre,
                                                                                    stime.hour, stime.minute, stime.second, stime.microsecond/1000,
                                                                                    etime.hour, etime.minute, etime.second, etime.microsecond/1000, ','.join(rest))
                        dst.write(line)
        except Exception as e: print(f'{bak} {line}')
